﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SilverlightDemoApp.Buttons
{
    /// <summary>
    /// Command button implementation
    /// </summary>
    public class CommandButton : Button
    {
        public CommandButton()
        {
            Click += (sender, e) =>
            {
                if (Command != null && Command.CanExecute(CommandParameter))
                    Command.Execute(CommandParameter);
            };
        }

        public static DependencyProperty CommandProperty =
            DependencyProperty.Register("Command",
                                        typeof(ICommand), typeof(CommandButton),
                                        new PropertyMetadata(null, CommandChanged));

        private static void CommandChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
        {
            var button = source as CommandButton;
            if (button == null) return;

            button.RegisterCommand(args.OldValue as ICommand, args.NewValue as ICommand);
        }

        private void RegisterCommand(ICommand oldCommand, ICommand newCommand)
        {
            if (oldCommand != null)
                oldCommand.CanExecuteChanged -= HandleCanExecuteChanged;

            if (newCommand != null)
                newCommand.CanExecuteChanged += HandleCanExecuteChanged;

            HandleCanExecuteChanged(newCommand, EventArgs.Empty);
        }

        private void HandleCanExecuteChanged(object sender, EventArgs args)
        {
            if (Command != null)
                IsEnabled = Command.CanExecute(CommandParameter);
        }

        public ICommand Command
        {
            get { return GetValue(CommandProperty) as ICommand; }
            set { SetValue(CommandProperty, value); }
        }

        public static DependencyProperty CommandParameterProperty =
            DependencyProperty.Register("CommandParameter",
                                        typeof(object), typeof(CommandButton),
                                        new PropertyMetadata(null));

        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }

    }
}